﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Authorize.Core.Store;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using Microsoft.Extensions.Logging;

namespace Authorize.Core.Authentication
{
    public class CustomProfileService : IProfileService
    {
        protected readonly ILogger Logger;
        private readonly UserStore _userStore;

        public CustomProfileService(ILogger<CustomProfileService> logger)
        {
            Logger = logger;
            _userStore = new UserStore();
        }

        public Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            context.LogProfileRequest(Logger);
            if (context.RequestedClaimTypes.Any())
            {
                var user = _userStore.FindBySubjectId(context.Subject.GetSubjectId());
                context.AddRequestedClaims(new []
                {
                    new Claim(CustomProfileDefault.UserName, user.Username ?? ""),
                    new Claim(CustomProfileDefault.NickName, user.Nickname ?? ""),
                    new Claim(CustomProfileDefault.Phone, user.Phone ?? ""),
                    new Claim(CustomProfileDefault.Email, user.Email ?? ""),
                    new Claim(CustomProfileDefault.Id, user.Id.ToString()), 
                    new Claim(CustomProfileDefault.OpenId, user.WeiChatOpenId ?? ""),
                    new Claim(CustomProfileDefault.Sex, user.Sex.ToString()),
                    new Claim(CustomProfileDefault.DeviceId, user.TerminalOpenId ?? ""), 
                    new Claim(CustomProfileDefault.AvartarUrl, user.AvartarUrl ?? ""),
                    new Claim(CustomProfileDefault.CreateDate, string.Format("{0:yyyy-MM-dd HH:mm:ss}", user.CreateDate)), 
                    new Claim(CustomProfileDefault.LastLoginDate, string.Format("{0:yyyy-MM-dd HH:mm:ss}", user.LastLoginDate))
                });
            }
            
            context.LogIssuedClaims(Logger);

            return Task.CompletedTask;
        }

        public Task IsActiveAsync(IsActiveContext context)
        {
            Logger.LogDebug("IsActive called from: {caller}", context.Caller);

            context.IsActive = true;
            return Task.CompletedTask;
        }
    }
}
